package com.nova.android.tvlauncher.ui.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import com.nova.android.tvlauncher.constants.ConstantsAtv
import sendLiveEventData

class ExternalDeviceReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                // 处理 USB 设备插入事件
                handleUsbDeviceAttached(context, device)
            }

            UsbManager.ACTION_USB_DEVICE_DETACHED -> {
                val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                // 处理 USB 设备拔出事件
                handleUsbDeviceDetached(context, device)
            }

            Intent.ACTION_MEDIA_MOUNTED -> {
                val mountPath = intent.dataString
                // 处理 TF 卡插入事件
                //"TF插入${mountPath}".e("zy2000")
                handleStorageMounted(context, mountPath)
            }

            Intent.ACTION_MEDIA_EJECT -> {
                val mountPath = intent.dataString
                // 处理 TF 卡拔出事件
                //"TF拔出${mountPath}".e("zy2000")
                handleStorageEjected(context, mountPath)
            }

            else -> {
                //"进入了其他".e("zy2000")
            }
        }
    }

    private fun handleUsbDeviceAttached(context: Context, device: UsbDevice?) {
        if (device != null) {
            // 获取设备信息并执行相应操作
            val deviceName = device.deviceName
            val vendorId = device.vendorId
            val productId = device.productId
            // ...
        }
    }

    private fun handleUsbDeviceDetached(context: Context, device: UsbDevice?) {
        if (device != null) {
            // 执行相应操作，例如释放资源
            // ...
        }
    }

    private fun handleStorageMounted(context: Context, mountPath: String?) {
        if (mountPath != null) {
            // 处理 存储设备插入事件，例如读取文件
            sendLiveEventData(ConstantsAtv.IS_INSERT_STORAGE, Pair(true, mountPath))
        }
    }

    private fun handleStorageEjected(context: Context, mountPath: String?) {
        if (mountPath != null) {
            // 处理 存储设备拔出事件，例如停止读取文件
            sendLiveEventData(ConstantsAtv.IS_INSERT_STORAGE, Pair(false, mountPath))
        }
    }
}